package models

import (
	"github.com/jinzhu/gorm"
)

const (
	MalCreated = 1 // 创建
	MalSolving = 2 // 正在解决
	MalSolved  = 3 // 已经解决
	MalNoSolve = 4 // 不解决

	MalSoftWave = 1 // 软件
	MalHardWave = 2 // 硬件
	MalNetWork  = 3 // 网络
	MalPower    = 4 // 电源
)

type Malfunction struct {
	// 模型基本属性
	Model

	// 关联用户
	UserID int  `json:"user_id" gorm:"index"`
	User   User `json:"user"`

	Room        string `json:"room"`
	Position    string `json:"position"`
	Type        int    `json:"type"`
	Description string `json:"description"`

	State int `json:"state"`
}

func ExistMalfunctionById(id int) (bool, error) {
	var mal Malfunction
	err := db.Select("id").Where("id = ? AND deleted_on = ?", id, 0).First(&mal).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return false, err
	}
	return mal.ID > 0, nil
}

func UpdateMalfunctionState(id, state int) error {
	err := db.Model(&Malfunction{}).Where("id = ? AND deleted_on = ?", id, 0).Set("state", state).Error
	return err
}

func AddMalfunction(data map[string]interface{}) error {
	mal := Malfunction{
		UserID:      data["user_id"].(int),
		Room:        data["room"].(string),
		Position:    data["position"].(string),
		Type:        data["type"].(int),
		Description: data["description"].(string),
		State:       MalCreated,
	}
	err := db.Create(&mal).Error

	return err
}

func GetMalfunctionTotal(maps interface{}) (int, error) {
	var count int
	err := db.Model(&Malfunction{}).Where(maps).Count(&count).Error
	if err != nil {
		count = 0
	}
	return count, err
}

func GetMalfunctions(pageNum int, pageSize int, maps interface{}) ([]*Malfunction, error) {
	var mals []*Malfunction
	err := db.Preload("User").Where(maps).Offset(pageNum).Limit(pageSize).Find(&mals).Error

	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return mals, nil
}

func DeleteMalfunction(id int) error {
	err := db.Where("id = ?", id).Delete(&Malfunction{}).Error
	return err
}

func CleanAllMalfunction() error {
	err := db.Unscoped().Where("deleted_on != ?", 0).Delete(&Malfunction{}).Error
	return err
}
